package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    MinioConstantProperties minioConstantProperties;

    @Autowired
    MinioClient minioClient;

    @SneakyThrows
    @Override
    public String fileUpload(MultipartFile file) {

        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
        if(!found){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
        } else {
            System.out.println("Bucket 'glsx' already exists.");
        }
        String fileName = String.valueOf(new Date().getTime());
        //String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        String originalFilename = file.getOriginalFilename();
        String extName = FilenameUtils.getExtension(originalFilename);
        String fullName = fileName + "." + extName;
        PutObjectArgs putObjectArgs = PutObjectArgs.builder().bucket(minioConstantProperties.getBucketName())
                .object(fullName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .build();
        minioClient.putObject(putObjectArgs);
        return minioConstantProperties.getEndpointUrl() + "/" +  minioConstantProperties.getBucketName() + "/" + fullName;
    }
}
